/**
 * Created by udi on 2016/11/26.
 */
let serve = require('koa-static');
let koa = require('koa');
let app = new koa();
let route = require('koa-route');
let jv = require("../libs/sys/myHelper").jv;
let request = require('request');
let qs = require('querystring');
let path = require('path');
const session = require("koa-session2");
let http = require('request-promise');
let init = require("./prepare").init;
var views = require('koa-views');
// var logger = require('koa-logger');
const compress = require('koa-compress');
const convert = require('koa-convert');

app.appConfig = require("./appConfig").appConfig;

app.routes = route;
global.app = app;


//app.use(html('.'));

// or use absolute paths

app.use(compress());
let notFound = async(ctx, next) => {
  ctx.status = 404;
  ctx.set("content-type", "text/html;charset=UTF-8");
  ctx.body = `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>404 找不到页面</title><meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" /></head><body><p class=main>
找不到页面
</p><pre style='font-size:small;margin:10px;'>
状态：404
请求路径：${ctx.req.url}
</pre></body></html>`;
};

app.use(serve(path.resolve(__dirname, '../../')));

app.use(async(ctx, next) => {
  let url = ctx.req.url;
  if (url) {
    let urlPart2 = url.split("?");
    url = urlPart2.slice[0] || "";
    if (url) {
      let lastPart = url.split("/").slice(-1)[0].split(".");
      if (lastPart.length > 1) {
        let ext = lastPart.slice(1).slice(-1)[0] || "";
        ext = ext.toLocaleLowerCase();
        ctx.req.urlExt = ext;
      }
    }
    if (urlPart2.length > 1) {
      let tokenQueryString = urlPart2[1].split("&").filter(it => {
        return it.startsWith("token=")
      });
      if (tokenQueryString && tokenQueryString.length) {
        ctx.req.token = tokenQueryString[0].split("=")[1];
      }
    }
  }
  ctx.req.urlExt = ctx.req.urlExt || "";

  if (ctx.req.urlExt && (["js", "css", "png", "icon", "ico", "jpg", "gif", "html", "appcache"].indexOf(ctx.req.urlExt) > -1)) {
    return await notFound(ctx, next);
  }

  return await next();
});

//app.use(serve(path.resolve(__dirname, '../../')));

// app.use(jade(path.join(__dirname, '../../html')));

const Pug = require('koa-pug');

const pug = new Pug({
  viewPath: path.resolve(__dirname, "../../html"),
  debug: true,
  pretty: true,
  compileDebug: true,
  locals: {
    rootdir: path.resolve(__dirname, "../../"), filename: function () {
      return __filename;
    }
  },
  //globals:{filename:"D:\\HaoHan\\wy_h5\\h5_vue\\bin\\main\\www.js"},
  // basedir: '',
  // helperPath: [
  //   'path/to/pug/helpers',
  //   { random: 'path/to/lib/random.js' },
  //   { _: require('lodash') }
  // ],
  app: app // equals to pug.use(app) and app.use(pug.middleware)
})

app.pug = pug;


var CONFIG = {
  key: 'KSESSIONID', /** (string) cookie key (default is koa:sess) */
  maxAge: 600000, /** (number) maxAge in ms (default is 10 min) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: false, /** (boolean) signed or not (default true) */
};
app.use(convert(session(CONFIG, app)));

app.use(init);

require('./routes');

app.use(notFound);

// app.on("error", (err, ctx) => {
//   jv.log(`In Error: ${err} ${ctx.req.url}`);
// });

let server = app.listen(app.appConfig.port, '0.0.0.0', () => {
  let host = server.address().address;
  let port = server.address().port;
  jv.log('service start:http://%s:%s', host ? host : '127.0.0.1', port);
});

